package com.boarsoft.boar.gateway.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;

import com.boarsoft.common.util.HttpClientUtil;
import com.boarsoft.common.util.JsonUtil;
import com.boarsoft.flow.core.bean.ProcessHandler;
import com.boarsoft.serialize.ObjectSerializer;

@Component("httpServiceProxy")
public class HttpServiceProxy implements ProcessHandler {
	private static final Logger log = LoggerFactory.getLogger(HttpServiceProxy.class);

	@Autowired(required = false)
	protected LoadBalancerClient balancer;
	/** 通过XML注入 */
	protected ObjectSerializer serializer;

	/** */
	protected int connectTimeout = 3000;
	/** */
	protected int readTimeout = 30000;
	/** */
	protected String contentType = "text/json";
	/** */
	protected String encIn = "UTF-8";
	/** 可选的负载均衡地址（如：Nginx），不能以/结尾 */
	protected String uri;

	@Override
	public Object process(String entry, Object data, Throwable throwable) throws Throwable {
		if (balancer != null) {
			log.info("Choose provider of service {}", entry);
			ServiceInstance si = balancer.choose(entry);
			uri = si.getUri().toString();
		}
		String url = new StringBuilder().append(uri)//
				.append("/").append(entry).toString();
		if (serializer == null) {
			String str = null;
			if (data instanceof java.lang.String) {
				str = (String) data;
			} else {
				str = JsonUtil.toJSONString(data);
			}
			log.info("Send http post to {}:\n{}\n", url, str);
			return HttpClientUtil.sendPost(url, contentType, encIn, str, null);
		}
		byte[] ba = serializer.serialize(data);
		return HttpClientUtil.sendPost(url, ba, url);
	}

	public int getConnectTimeout() {
		return connectTimeout;
	}

	public void setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
	}

	public int getReadTimeout() {
		return readTimeout;
	}

	public void setReadTimeout(int readTimeout) {
		this.readTimeout = readTimeout;
	}

	public LoadBalancerClient getBalancer() {
		return balancer;
	}

	public void setBalancer(LoadBalancerClient balancer) {
		this.balancer = balancer;
	}

	public ObjectSerializer getSerializer() {
		return serializer;
	}

	public void setSerializer(ObjectSerializer serializer) {
		this.serializer = serializer;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getEncIn() {
		return encIn;
	}

	public void setEncIn(String encIn) {
		this.encIn = encIn;
	}

	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}
}
